import { AfterViewChecked, Component, ElementRef, HostListener, Input, OnInit, ViewChild } from '@angular/core';
import { Todo } from '../todo.model';
import { TodoService } from '../todo.service';

@Component({
  selector: 'app-todo-item',
  templateUrl: './todo-item.component.html',
  styleUrls: ['./todo-item.component.css']
})
export class TodoItemComponent implements OnInit, AfterViewChecked {

  @Input() todo: Todo;

  @ViewChild('edit') editRef: ElementRef;

  private lastContent: string;

  constructor(
    private readonly todoService: TodoService
  ) { }

  ngOnInit(): void {
  }

  ngAfterViewChecked(): void {
    if (this.todo.editing) {
      this.editRef?.nativeElement.focus();
    }
  }

  onItemDoubleClicked(): void {
    this.startEditing();
  }

  @HostListener('document:click', [ '$event' ])
  clickOutside(event): void {
    if (!this.editRef?.nativeElement.contains(event.target)) {
      this.cancelEditing();
    }
  }

  onEditClicked(event: MouseEvent): void {
    event.stopPropagation();
  }

  onCompletedClicked(): void {
    this.todoService.update(this.todo);
  }

  finishEditing(): void {
    this.todo.editing = false;
    if (this.todo.content.trim().length === 0) {
      this.todoService.remove(this.todo.id);
    } else {
      this.todoService.update(this.todo);
    }
  }

  cancelEditing(): void {
    if (this.todo.editing) {
      this.todo.content = this.lastContent;
      this.todo.editing = false;
      this.todoService.update(this.todo);
    }
  }

  onDeleteClicked(): void {
    this.todoService.remove(this.todo.id);
  }

  private startEditing(): void {
    this.lastContent = this.todo.content;

    this.todo.editing = true;
    this.todoService.update(this.todo);
  }

}
